package com.yaoran.userauth.service.impl;

import com.yaoran.userauth.config.redis.RedisUtils;
import com.yaoran.userauth.dao.LoginDao;
import com.yaoran.userauth.entity.User;
import com.yaoran.userauth.service.LoginService;
import com.yaoran.userauth.utils.R;
import com.yaoran.userauth.utils.TokenUtil;
import com.yaoran.userauth.vo.request.UserRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    private final static Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
    @Autowired
    private LoginDao loginDao;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public R authLogin(UserRequest userRequest){
        /*List<User> user = loginDao.getUser(userRequest.getUsername(),userRequest.getPassword());
        if(user.size() == 0){
            log.error("登录失败："+userRequest);
            return R.error("用户名或密码错误");
        }else {
            User obj = user.get(0);
            String token = tokenUtil.getToken(obj.getName(),String.valueOf(obj.getRoleId()));
            log.info("登录成功："+userRequest+token);
            return R.ok().put("data",token);
        }*/
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token =
                new UsernamePasswordToken(userRequest.getUsername(),userRequest.getPassword());
        try{
            currentUser.login(token);
            String encryptToken = tokenUtil.getToken(userRequest.getUsername(),userRequest.getPassword());
            return R.ok(encryptToken);
        }catch (AuthenticationException e){
            return R.error("用户名或密码错误");
        }
    }

    @Override
    public User getUserByName(String username){
        return loginDao.queryByUsername(username);
    }
}
